package com.fly.estore.service.Impl;

import com.fly.estore.dao.StockDAO;
import com.fly.estore.dao.StockDetailDAO;
import com.fly.estore.domain.StockDetail;
import com.fly.estore.domain.StockInfo;
import com.fly.estore.framework.util.CommonUtil;
import com.fly.estore.service.StockService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by Fly on 2016/4/26.
 */
@Service("StockService")
public class StockServiceImpl implements StockService {

    @Autowired
    StockDAO stockDAO;
    @Autowired
    StockDetailDAO stockDetailDAO;

    public int saveStockInfo(StockInfo stockInfo) {
        int update = 0;
        if (StringUtils.isBlank(stockInfo.getStockId())){
            //新增
            stockInfo.setStockId(CommonUtil.genPK());
            update = stockDAO.addStock(stockInfo);

            for(StockDetail detail: stockInfo.getDetailList()){
                detail.setStockDetailId(stockInfo.getStockId());
                stockDetailDAO.addStockDetail(detail);
            }
        }
        else{
            update = stockDAO.updateStock(stockInfo);
        }
        return update;
    }

    public int deleteStockById(String stockId) {
        int update = 0;
        update = stockDAO.deleteById(stockId);
        stockDetailDAO.deleteByStockId(stockId);
        return update;
    }

    public StockInfo getStockById(String stockId) {
        StockInfo stock = stockDAO.getById(stockId);
        if (null != stock){
            stock.setDetailList(stockDetailDAO.getByStockId(stockId));
        }
        return stock;
    }

    public List<StockInfo> getStockList() {
        return stockDAO.getList();
    }

    public int saveStockDetail(StockDetail stockDetail) {
        int update = 0;
        if (StringUtils.isBlank(stockDetail.getStockDetailId())){
            stockDetail.setStockDetailId(CommonUtil.genPK());
            update = stockDetailDAO.addStockDetail(stockDetail);
        }
        else{
            update = stockDetailDAO.updateStockDetail(stockDetail);
        }
        return update;
    }

    public List<StockDetail> getStockDetailList() {
        return stockDetailDAO.getList();
    }

    public StockDetail getDetailById(String stockDetailId) {
        return stockDetailDAO.getById(stockDetailId);
    }

    public int deleteStockDetail(String stockDetailId) {
        return stockDetailDAO.deleteById(stockDetailId);
    }
}
